import 'package:fluent_ui/fluent_ui.dart';

import '../../api/dict_api.dart';
import '../../model/dict_model.dart';

///应用字典数据
class AppDictData {
  AppDictData._();

  static final _singleton = AppDictData._();

  factory AppDictData() => _singleton;

  final _dictMap = <String, Map<String, DictDataRes>>{};

  ///加载字典数据
  Future<List<DictDataRes>> itemsByCode(final String dictCode) {
    if (dictCode.isNotEmpty) {
      final map = _dictMap[dictCode];
      if (map == null || map.isEmpty) {
        return dictApi.dict(DictDataReq(code: dictCode)).then((items) {
          final map_ = <String, DictDataRes>{};
          if (items.isNotEmpty) {
            for (var item in items) {
              map_[item.val] = item;
            }
            _dictMap[dictCode] = map_;
          }
          return map_.values.toList();
        });
      } else {
        return Future<List<DictDataRes>>.value(map.values.toList());
      }
    }
    return Future<List<DictDataRes>>.value([]);
  }

  ///构建字典选项集合
  Future<List<ComboBoxItem<String>>> buildOpts(final String dictCode) {
    return itemsByCode(dictCode).then((items) {
      final opts = <ComboBoxItem<String>>[];
      if (items.isNotEmpty) {
        for (var item in items) {
          opts.add(ComboBoxItem<String>(
            value: item.val,
            child: Text(item.label),
          ));
        }
      }
      return opts;
    });
  }

  ///获取字典标签名称集合
  String getLabels<T>(final String dictCode, final List<T?>? vals) {
    if (dictCode.isNotEmpty && vals != null && vals.isNotEmpty) {
      final map = _dictMap[dictCode];
      if (map != null && map.isNotEmpty) {
        final labels = <String>[];
        for (var val in vals) {
          if (val == null) {
            continue;
          }
          final data = map['$val'];
          if (data != null && data.label.isNotEmpty) {
            labels.add(data.label);
          }
        }
        return labels.join(',');
      }
    }
    return '';
  }

  ///获取字典标签名称
  String getLabel<T>(final String dictCode, final T? val) =>
      getLabels(dictCode, [val]);
}

///应用字典数据单例
final appDictData = AppDictData();
